/**
 * 目前作用在入转调离设置-劳动合同上传页面
 * 实现文件的上传预览，以及删除，重新上传
 * 仿制上个页面
 * auto:hongzequan
 */
import React from 'react';
import { Icon, Spin, Divider, Popconfirm, Tooltip } from 'antd';
import UploadOss from '@/components/UploadOss';
import IconPro from '@/components/IconPro';
import { ResumeIframe } from '@/pages/Recruitment/components';
import cookie from 'js-cookie';
import _ from 'lodash';
import Styles from './index.less';

/**
 *
 * @param {*} previewUrl 预览url地址
 * @param {*} fileLists 后端返回的附件对象
 * @param {*} setFileLists 删除的时候要用到。
 * @param {*} disabled 不可点击，详情页用
 * @param {*} onChange change回调
 * @param {*} onPreviewChange 文件上传后的回调
 * @param {*} onDelete 文件删除后的回调
 * @param {*} setFormUploading 用来给外面使用这个组件的loading设置，要不然在上传过程中没办法禁止表单提交
 * @returns
 */
export default function FilePreviewAndUpload({
    previewUrl = '',
    uploadConfig,
    fileLists = '',
    disabled = false,
    setFileLists = () => {},
    onChange = () => {},
    onPreviewChange = () => {},
    onDelete = () => {},
    setFormUploading = () => {}
}) {
    const [uploading, setUploading] = React.useState(false);
    const [fileList, setFileList] = React.useState();
    const [fileName, setFileName] = React.useState();

    const isNative = /\.pdf(\?.*)?$/.test(previewUrl);

    const url = isNative
        ? previewUrl
        : `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(previewUrl)}`;

    const handleUpload = async _res => {
        // 服务端实现兼容，暂不建议封装。
        fetch('/api/resource/oss/produceGetPreSignUrls', {
            body: JSON.stringify({
                businessCode: uploadConfig?.businessCode || 'Contract',
                sysCode: 'OA',
                fileList: _res
            }),
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json; charset=utf-8',
                Authorization: cookie.get('Authorization')
            }
        })
            .then(response => response.json())
            .then(myJson => {
                const { data } = myJson;
                const { fileList: files = [] } = data || {};
                onPreviewChange(files[0]?.preUrl);
                setUploading(false);
                if (setFormUploading) {
                    setFormUploading(false);
                }
            });
    };
    // 文件合同右上角的删除跟重新上传按钮逻辑判断
    const renderRightButton = () => {
        if (disabled) {
            return null;
        }
        if (_.size(fileList) > 0 || _.size(fileLists) > 0) {
            return (
                <div className={Styles.rightWarp}>
                    <Popconfirm
                        placement="top"
                        title="确定删除？"
                        onConfirm={() => {
                            // 删除file组件内文件
                            setFileList([]);
                            // 删除外部传进来的file
                            setFileLists([]);
                            // 删除文件名
                            setFileName('');
                            onDelete();
                        }}
                        okText="确定"
                        cancelText="取消"
                    >
                        <a disabled={uploading} style={{ color: 'rgb(0 0 0 / 45%)' }} className={Styles.buttons}>
                            <IconPro
                                type="iconDeleteIcon"
                                style={{
                                    marginRight: 8,
                                    fontSize: 20,
                                    color: 'rgb(0 0 0 / 65%)',
                                    lineHeight: '20px',
                                    height: '20px'
                                }}
                            />
                            删除
                        </a>
                    </Popconfirm>

                    <Divider type="vertical" />
                    <UploadOss
                        uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                        sysCode="OA"
                        categoryCode="newContractVersion"
                        onUploaded={handleUpload}
                        onChange={({ file = {} }) => {
                            if (file.status === 'uploading') {
                                setUploading(true);
                                if (setFormUploading) {
                                    setFormUploading(true);
                                }
                            }
                        }}
                        fileList={fileList}
                        setFileList={(_fileList, uploadResourceResult) => {
                            setFileName(_fileList[_fileList.length - 1].name);
                            setFileList([_fileList[_fileList.length - 1]]);
                            onChange(uploadResourceResult);
                        }}
                        checkFileSize={50}
                        checkFileType="pdf、doc、xls、docx、wps"
                        checkFileTypeMsg="只能上传 pdf、doc、xls、docx、wps 格式的文件！"
                        checkFileSizeMsg="文件大小不能超过50MB！"
                        showUploadList={false}
                        showPreviewFile
                        disabled={uploading}
                        {...uploadConfig}
                    >
                        <a style={{ color: 'rgb(0 0 0 / 45%)' }} className={Styles.buttons}>
                            <IconPro
                                type="iconsearchbar_export_icon_default"
                                style={{
                                    marginRight: 8,
                                    fontSize: 20,
                                    color: 'rgb(0 0 0 / 65%)',
                                    lineHeight: '20px',
                                    height: '20px'
                                }}
                            />
                            重新上传
                        </a>
                    </UploadOss>
                </div>
            );
        }
        return '';
    };

    return (
        <div className={Styles.ResumePreviews}>
            <div className={Styles.header}>
                <Tooltip placement="topLeft" title={fileName || fileLists?.originName}>
                    <div className={Styles.ResumePreviewsTitle}>
                        {fileName || fileLists?.originName || '上传文件后将自动生成预览'}
                    </div>
                </Tooltip>

                {renderRightButton()}
            </div>
            <div className={Styles.bodyContent}>
                {!previewUrl && (
                    <Spin spinning={uploading}>
                        <UploadOss
                            style={{ maxWidth: '420px', height: '195px', margin: '50px auto 100px' }}
                            dragAble
                            uploadUrl="/api/resource/public/oss/producePutPreSignUrls"
                            sysCode="OA"
                            categoryCode="newContractVersion"
                            onUploaded={handleUpload}
                            onChange={({ file = {} }) => {
                                if (file.status === 'uploading') {
                                    setUploading(true);
                                    if (setFormUploading) {
                                        setFormUploading(true);
                                    }
                                }
                            }}
                            fileList={fileList}
                            setFileList={(_fileList, uploadResourceResult) => {
                                setFileName(_fileList[_fileList.length - 1].name);
                                setFileList([_fileList[_fileList.length - 1]]);
                                onChange(uploadResourceResult);
                            }}
                            checkFileSize={20}
                            checkFileType="pdf、doc、xls、docx、wps"
                            checkFileTypeMsg="只能上传pdf、doc、xls、docx、wps格式的文件！"
                            checkFileSizeMsg="文件大小不能超过50MB！"
                            showUploadList={false}
                            showPreviewFile
                            {...uploadConfig}
                        >
                            <p className="ant-upload-drag-icon">
                                <Icon type="inbox" style={{ color: 'rgb(0 0 0 / 25%)' }} />
                            </p>
                            <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
                            <p className="ant-upload-hint">
                                支持 {uploadConfig?.checkFileType || 'pdf、doc、xls、docx、wps'}
                                等格式文件，单个文件大小为20M以内
                            </p>
                        </UploadOss>
                    </Spin>
                )}
                {previewUrl && <ResumeIframe url={url} isNative={isNative} />}
            </div>
        </div>
    );
}
